var jstree = $.tree_create();
$(function() {
	jstree.init($('#tree'), {
		cookies: {},
		ui: {
			dots: false,
			animation: 250,
			context: false
		},
		rules: {
			draggable: ['all'],
			dragrules: [
				'template before template',
				'template after template'
			]
		},
		callback: {
			onchange: function(node, tree_obj) {
				$.get('?id='+node.id);
			},
			onmove: function(node, ref_node, type, tree_obj) {
				$.post('actions/move/', { id: $(node).attr('id'), ref_id: $(ref_node).attr('id'), type: type }, function(responseJson) {
				}, 'json');
			},
			ondelete: function(node, tree_obj) {
				$.post('actions/delete/', { id: $(node).attr('id') }, function(responseJson) {
				}, 'json');
			},
			onload: function(tree_obj) {
				$('#tree').find('.no-children').removeClass('open').removeClass('closed');
				if (!$('#tree a.clicked').length) {
					$('#tree a:first').click();
				}
			},
			onopen: function(node, tree_obj) {
				$(node).find('.no-children').removeClass('open').removeClass('closed').removeClass('no-children');
			}
		}
	});
	
	function jstree_create() {
		$.post('actions/create/', { after_id: jstree.selected.attr('id') }, function(responseJson) {
				var new_li = jstree.create({
					"attributes": {
						"id": responseJson.id,
						"rel": "template"
					},
					"state": "closed",
					"data": {
						"title":"Untitled template",
						"icon":"/admin/backend/resources/images/icons/layout.png"
					}
				}, null, 'after');
				jstree.select_branch(new_li);
				new_li.removeClass('open').removeClass('closed');
			$("ul.tabs").tabs('select', 0);
		}, 'json');
	}
	
	function jstree_create1() {
		$.post('actions/create/', { after_id: jstree.selected.attr('id') }, function(responseJson) {
			var new_li = jstree.create(jstree, null, 'after');
			jstree.select_branch(new_li);
			$(new_li).find('input').val('Untitled template');
			$(new_li).find('input').blur();
			$(new_li).attr('id', responseJson.id);
			$(new_li).attr('rel', 'template');
			$(new_li).find('a').css('background-image', 'url(/admin/backend/resources/images/icons/layout.png)');
			$.get('?', { id: responseJson.id });
			$("ul.tabs").tabs('select', 0);
		}, 'json');
	}
	
	$('a.create:not(.disabled)').livequery('click', function(e) {
		e.preventDefault();
		jstree_create();
	});
	$('a.delete:not(.disabled)').livequery('click', function(e) {
		e.preventDefault();
		jstree.remove();
	});
	
	
	$("ul.tabs").tabs();
	if (!$('#tree a.clicked').length) {
		$('#tree a:first').click();
	}
	
	/*
	 * Plugins
	 *
	 */
	$('table.plugins textarea').attr('wrap', 'off').livequery('focus', function() {
		$(this).animate({ height: 250 }, 250);
	}).livequery('blur', function() {
		$(this).animate({ height: 50 }, 250);
	});
	$('table.plugins input[type=checkbox]').livequery('change', function() {
		if ($(this).is(':checked')) {
			$('#' + $(this).closest('tr').attr('id') + '_config').show();
		} else {
			$('#' + $(this).closest('tr').attr('id') + '_config').hide();
		}
	});
	
});